/*
 Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
 Original sources are available at www.latestbit.com

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 ManagedClient.hpp. Created on: 11.09.2009 12:32:21
 */

#ifndef MANAGEDCLIENT_HPP_
#define MANAGEDCLIENT_HPP_

#include "smartobjects/SmartObjectsDefs.hpp"
#include "INetworkFactory.hpp"
#include "IManagedClient.hpp"
#include "ConnectionHandler.hpp"
#include "ManagedConnection.hpp"
#include "IManagedConnectionFactory.hpp"

namespace smartobjects {

class ManagedClient : public IManagedClient, public ManagedConnection, public IManagedConnectionFactory {
public:
	SO_DLLPRFX ManagedClient(INetworkFactory*);
	SO_DLLPRFX virtual ~ManagedClient();

	SO_DLLPRFX virtual void setEndpointLocation(IEndpointLocation* poLocation, IEndpointCoordinator* poCoordinator);

	SO_DLLPRFX virtual void start();
	SO_DLLPRFX virtual void start(unsigned long nAwaitTimeInSec);
	SO_DLLPRFX virtual void stop();

	SO_DLLPRFX virtual void fireOnConnected();
	SO_DLLPRFX virtual void fireOnConnectionFailure(ConnectionHandler* poHandler, const std::string& sErrorMessage);
	SO_DLLPRFX virtual void fireOnDisconnected(ConnectionHandler* poHandler);

	SO_DLLPRFX virtual IManagedConnection* createManagedConnection();
	SO_DLLPRFX virtual void removeManagedConnection(IManagedConnection*);

protected:
	SO_DLLPRFX void updateConnectors();
	SO_DLLPRFX void restoreConnection(ConnectionHandler* handler);

protected:
	INetworkFactory* m_poNetworkFactory;
	bool m_bStarted;

	typedef boost::unordered_map<std::string, IConnector*> ConnectorsMap;
	ConnectorsMap m_mConnectors;
	Handlers m_aAllHandlers;
	boost::recursive_mutex m_mxConnectors;

	boost::condition m_evAwaitConnect;
	boost::recursive_mutex m_mxAwaitConnect;

};

}

#endif /* MANAGEDCLIENT_HPP_ */
